package com.gitee.jjnnzb.designpatterninspring.business.login.handler;

import com.gitee.jjnnzb.designpatterninspring.business.login.entity.vo.TokenRt;
import com.gitee.jjnnzb.designpatterninspring.common.bean.CommonException;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Jjn
 * @since 2023/8/8 13:43
 */
@Component
@RequiredArgsConstructor
public class LoginStrategy {
    
    /**
     * Spring 注入LoginTemplate相关的全部实现类
     */
    private final List<LoginTemplate> templates;
    /**
     * 策略Map, Key为版本号
     */
    private Map<String, LoginTemplate> loginTemplateMap;
    
    @PostConstruct
    public void init() {
        loginTemplateMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(templates)) {
            templates.forEach(loginTemplate -> loginTemplateMap.put(loginTemplate.getVersion(), loginTemplate));
        }
    }
    
    /**
     * 业务处理统一入口
     *
     * @param map 请求上下文
     * @return 处理结果
     */
    public TokenRt login(Map<String, Object> map) {
        String version = (String) map.get("version");
        if (StringUtils.isBlank(version)) {
            throw new CommonException("未知版本");
        }
        LoginTemplate loginTemplate = loginTemplateMap.get(version);
        if (loginTemplate == null) {
            throw new CommonException("未找到对应的版本");
        }
        return loginTemplate.login0(map);
    }
}
